<template>
  <transition :duration="300" @afterLeave="afterLeave">
    <div class="dialog-container" @click.stop="outSideClick" v-if="open">
      <div class="overlay" v-if="dark"></div>
      <div class="dialog">
        <div class="title" v-if="title">{{ title }}</div>
        <div class="content">{{ content }}</div>
        <div class="btn-group">
          <div class="btn-item btn-cancel" @click.stop="cancelClick">取消</div>
          <div class="btn-item btn-confirm" @click.stop="confirmClick">确定</div>
        </div>
      </div>
    </div>
  </transition>
</template>

<script>
import {ref, onMounted} from 'vue'

export default {
  name: "CommonDialog",
  props: {
    dark: Boolean,
    outSideCancel: {
      type: Boolean,
      default: true
    },
    title: String,
    content: String,
    onConfirm: Function,
    onCancel: Function,
    onDismiss: Function
  },
  setup(props) {
    const open = ref(false)
    const {dark, outSideCancel, title, content, onConfirm, onCancel, onDismiss} = props
    const close = () => {
      open.value = false;
    }
    const outSideClick = () => {
      if (outSideCancel) {
        cancelClick()
      }
    }
    const cancelClick = () => {
      if (onCancel) {
        if (onCancel(close)) {//返回 true,则不关闭弹窗
          return
        }
      }
      close()
    }
    const confirmClick = () => {
      if (onConfirm) {
        if (onConfirm(close)) {//返回 true,则不关闭弹窗
          return
        }
      }
      close()
    }
    const afterLeave = () => {
      if (onDismiss) {
        onDismiss()
      }
    }
    onMounted(() => {
      open.value = true;
    })

    return {
      open,
      dark,
      title,
      content,
      outSideClick,
      cancelClick,
      confirmClick,
      afterLeave
    }
  },

}
</script>

<style lang="less" scoped>
@import "/src/utils/style/color";

.overlay {
  width: 100%;
  height: 100%;
  background-color: @overlay-dark;
  transition: all 0.3s;
}

.dialog {
  position: absolute;
  background: @white;
  border-radius: 8px;
  width: 260px;
  box-shadow: 0 0 3px 1px @shadow-color;
  left: 0;
  right: 0;
  top: 35%;
  margin: 0 auto;
  transition: all 0.3s;
}

.v-enter-from {
  .overlay {
    opacity: 0;
  }

  .dialog {
    transform: scale(0.3, 0.3);
    opacity: 0;
  }
}

.v-leave-to {
  .overlay {
    opacity: 0;
  }

  .dialog {
    opacity: 0;
  }
}

.title {
  text-align: center;
  font-size: 16px;
  font-weight: bold;
  color: @text-color;
  margin-top: 12px;
}

.content {
  text-align: center;
  font-size: 14px;
  color: @text-color2;
  margin: 12px;
}

.btn-group {
  height: 40px;
  display: flex;
  flex-direction: row;
  border-top: 1px solid @gray2;

  .btn-item {
    flex: 1;
    line-height: 40px;
    text-align: center;
    font-size: 15px;
  }
}


.btn-cancel {
  color: @gray1;
  border-right: 1px solid #eee;
}

.btn-confirm {
  color: @global;
}
</style>
